package com.fjut.zr.judge_system.OJ;

import com.fjut.zr.judge_system.OJ.OJS.BaseOJ;
import com.fjut.zr.judge_system.OJ.OJS.CLanguage;
import com.fjut.zr.judge_system.OJ.OJS.CppLanguage;
import com.fjut.zr.judge_system.OJ.OJS.Java;
import com.fjut.zr.judge_system.POJO.VO.OJSubmitinfo;
import com.fjut.zr.judge_system.POJO.PO.TOjStatusPO;
import com.fjut.zr.judge_system.POJO.PO.TOjSubmitPO;
import com.fjut.zr.judge_system.Util.ApplicationContextHelper;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class OjSubmitter implements Runnable {
    //正在处理的info
    public OJSubmitinfo info;
    OJSubmitinfo zanshi;//暂存info
    //忙碌状态与否0代表空闲1代表繁忙
    int status;
    //测评机ID
    int submitterID;
    int ojid;
    Ojudge ojudge;
    String OjName;
    public String submitPath;
    public String dataPath;
    private TOjSubmitPO ojSubmitInfoPO=new TOjSubmitPO();
    private TOjStatusPO ojStatusPO=new TOjStatusPO();
    //获取测评机线程
    private Thread selfThread = null;
    private String ojsrid;
    public OjSubmitter(int ojid,int id, Ojudge ojudge){
        this.ojid=ojid;
        submitterID = id;
        this.ojudge = ojudge;
    }
    @Override
    public void run() {
        /**
         * 创建一个
         * 核心线程数为20
         * 最大线程数为80
         * 线程最大存活时间为10秒
         * 工作队列是一个由链表结构组成的有界阻塞队列（大小为10）
         * 拒绝策略为抛弃最老的任务
         */
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 400,
                10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10),
                new ThreadPoolExecutor.DiscardPolicy());
        while(true){
            try {
                this.info=ojudge.queue.get(ojid).take();//阻塞队列
                BaseOJ judge = null;
                switch (ojid){
                    case 0:
                        judge=new Java();
                        break;
                    case 1:
                        judge=new CLanguage();
                        break;
                    case 2:
                        judge=new CppLanguage();
                        break;
                    default:
                        break;
                }
                judge.submit(info.getRid(),info.getPid(),info.getTime(),info.getMemory(),info.getCode());
                threadPool.execute(judge);
            } catch (Exception e) {
                this.status=0;
                System.out.println(e);
                System.out.println(OjName+submitterID+":出错，10秒后重新运行");
                //线程暂停10秒
                try { Thread.sleep(10000); } catch (InterruptedException ignored) { }
            }
        }
    }
    public void setSelfThread(Thread selfThread) {
        this.selfThread = selfThread;
    }

    public String getOjsrid() {
        return ojsrid;
    }
}
